package parser;

import model.Graph;
import model.Noeud;
import test.Test;
import view.drawable.NoeudDrawable;

import java.awt.*;
import java.io.*;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * User: Thomas
 * Date: 08/02/14
 * Time: 12:16
 * Classe permettant la gestion de la sauvegarde et du chargement des fichiers contenant la position en px des noeuds
 */
public class GraphFilePxPosition {
    /**
     * Sauvegarde de la position des noeuds
     * @param graph actuel
     * @throws FileNotFoundException
     * @throws UnsupportedEncodingException
     */
    public static void save(Graph graph) throws FileNotFoundException, UnsupportedEncodingException {
        PrintWriter writer = new PrintWriter(Test.getGraphFile().getGraph2pxFilename(), "UTF-8");

        for(Map.Entry<Integer, Noeud> entry : graph.getNoeuds().entrySet()) {
            Noeud noeud = entry.getValue();
            NoeudDrawable noeudDrawable = noeud.getNoeudDrawable();
            writer.println(noeud.getId() + " " + noeudDrawable.getPosition().getX() + " " + noeudDrawable.getPosition().getY());
        }

        writer.close();
    }

    /**
     * Chargement de la position des noeuds
     * @param graph choisi
     * @throws IOException
     */
    public static void read(Graph graph) throws IOException {

        FileReader fileInputStream = new FileReader(Test.getGraphFile().getGraph2pxFilename());
        BufferedReader br=new BufferedReader(fileInputStream);
        String ligne;
        while ((ligne = br.readLine()) != null){
            //lecture des noeuds
            String[] arguments_noeud = ligne.split(" ",3);
            int id_noeud = Integer.parseInt(arguments_noeud[0]);
            Noeud noeud = graph.getNoeuds().get(id_noeud);
            if (noeud != null) {
                noeud.getNoeudDrawable().setPosition(new Point((int) Double.parseDouble(arguments_noeud[1]), (int) Double.parseDouble(arguments_noeud[2])));
            }
        }
        br.close();
    }
}
